<template>
    <div>
        <div class="headerTit">
            <el-form :model="form" ref="queryForm" :inline="true" label-width="100px">
                <el-form-item label="工作流程名字:" prop="name">
                    <el-input v-model="form.name" placeholder="请输入流程名字" clearable size="small" disabled />
                </el-form-item>
                <el-form-item label="业务类型:" prop="category">
                    <el-select v-model="form.category" placeholder="请选择状态" disabled>
                        <el-option v-for="dict in dict.type.bus_flow_type" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </div>
        <bpmn-modeler ref="refNode" :xml="xml" :users="users" :groups="groups" :config="config" :categorys="categorys"
            :exps="exps" :is-view="false" @save="save" @showXML="showXML" :state="state" />
        <!--在线查看xml-->
        <el-drawer :title="xmlTitle" :modal="false" direction="rtl" :visible.sync="xmlOpen" size="60%">
            <!-- 设置对话框内容高度 -->
            <el-scrollbar>
                <pre v-highlight="xmlData"><code class="xml"></code></pre>
            </el-scrollbar>
        </el-drawer>
    </div>
</template>
<script>
import {
    roleList,
    saveXml,
    userList,
    expList,
    SaveModelConfig,
} from "@/api/flowable/definition";
import bpmnModeler from "@/components/Process/index";
import vkBeautify from "vkbeautify";
import hljs from "highlight.js";
import "highlight.js/styles/atelier-savanna-dark.css";
import { readXml } from "@/api/flowable/model";
import Cookies from "js-cookie";
import { Base64 } from "js-base64";

export default {
    name: "Model",
    dicts: ["bus_flow_type"],
    components: {
        bpmnModeler,
        vkBeautify,
    },
    computed: {
        type() {
            return this.$route.query.type;
        },
        modelId() {
            return this.$route.query.modelId;
        },
        state() {
            return this.$route.query.state;
        },
    },
    // 自定义指令
    directives: {
        deep: true,
        highlight: {
            deep: true,
            bind: function bind(el, binding) {
                const targets = el.querySelectorAll("code");
                let target;
                let i;
                for (i = 0; i < targets.length; i += 1) {
                    target = targets[i];
                    if (typeof binding.value === "string") {
                        target.textContent = binding.value;
                    }
                    hljs.highlightBlock(target);
                }
            },
            componentUpdated: function componentUpdated(el, binding) {
                const targets = el.querySelectorAll("code");
                let target;
                let i;
                for (i = 0; i < targets.length; i += 1) {
                    target = targets[i];
                    if (typeof binding.value === "string") {
                        target.textContent = binding.value;
                        hljs.highlightBlock(target);
                    }
                }
            },
        },
    },
    data() {
        return {
            xml: "", // 后端查询到的xml
            modeler: "",
            xmlOpen: false,
            xmlTitle: "",
            xmlData: "",
            users: [],
            groups: [],
            categorys: [],
            exps: [],
            form: {
                name: "",
                category: "",
            },
            config: [],
        };
    },
    created() {
        const info = {
            // deployId: this.$route.query && this.$route.query.deployId,
            modelId: this.$route.query && this.$route.query.modelId,
        };
        this.$set(this.form, "name", this.$route.query.name);
        this.$set(this.form, "category", this.$route.query.category);
        //  查询流程xml
        if (this.$route.query && this.$route.query.modelId) {
            this.getXmlData(info);
        }
        this.getDicts("sys_process_category").then((res) => {
            this.categorys = res.data;
        });
        this.getDataList();
    },
    methods: {
        /** xml 文件 */
        getXmlData(info) {
            // 发送请求，获取xml
            readXml(info).then((res) => {
                this.xml = res.data.xml;
                this.modeler = res.data.xml;
                this.config = res.data.config;
            });
        },
        validateForm(obj, index, name, options = []) {
            if (options == "all") {
                options = [
                    {
                        key: "activityName",
                        label: "节点名称",
                    },
                    {
                        key: "formId",
                        label: "流程表单",
                    },
                    {
                        key: "pageAddress",
                        label: "关联页面地址",
                    },
                    {
                        key: "activityPermission",
                        label: "节点权限",
                    },
                    {
                        key: "auditConfig",
                        label: "审批设置",
                    },
                    // {
                    //     key: "rejectActivity",
                    //     label: "驳回节点",
                    // },
                    {
                        key: "isCopy",
                        label: "是否抄送",
                    },
                    {
                        key: "copyUserIds",
                        label: "抄送人员",
                    },
                    {
                        key: "candidateGroups",
                        label: "审批角色",
                    },
                    {
                        key: "isPortUser",
                        label: "审批人员",
                    },
                    {
                        key: "candidateUsers",
                        label: "审批用户",
                    },
                    {
                        key: "refuseUserIds",
                        label: "可拒绝用户",
                    },
                    {
                        key: "isAvgUser",
                        label: "任务分配",
                    },
                    {
                        key: "flowType",
                        label: "节点审核权限",
                    },
                ];
            } else {
                if (options.length == 0) return true;
            }
            let result = true;
            for (let [k, v] of Object.entries(obj)) {
                let validate = options?.find((e) => e.key == k);
                if (
                    (v === null ||
                        v === undefined ||
                        v === "" ||
                        v?.length === 0) &&
                    validate?.label
                ) {
                    result = false;
                    if (k == "rejectActivity" && index == 0) {
                        result = true;
                    }
                    if (
                        (k == "flowType" || k == "candidateGroups") &&
                        obj?.isPortUser
                    ) {
                        result = true;
                    }
                    if (k == "candidateUsers" && !obj?.isPortUser) {
                        result = true;
                    }
                    if (k == "copyUserIds" && !obj?.isCopy) {
                        result = true;
                    }
                    if (!result) {
                        this.$message.error(
                            `${name}的${validate.label}不能为空`
                        );
                        break;
                    }
                }
            }
            return result;
        },
        /** 保存xml */
        async save(data) {
            let pass = true;
            for (let i = 0, len = data.rejectNode?.length ?? 0; i < len; i++) {
                let item = data?.rejectNode?.[i];
                if (item.isCopy === "true") {
                    item.isCopy = true;
                }
                if (item.isCopy === "false") {
                    item.isCopy = false;
                }
                if (item.isPortUser === "true") {
                    item.isPortUser = true;
                }
                if (item.isPortUser === "false") {
                    item.isPortUser = false;
                }
                let result = this.validateForm(
                    item,
                    i,
                    item?.activityName,
                    "all"
                );
                pass = result;
                if (!result) break;
            }
            if (!pass) return;
            let xmlblob = new Blob([data.xml]);
            let xmlFile = new File([xmlblob], `1.bpmn20.xml`, {
                type: "application/xml",
            });
            let params_file = new FormData();
            params_file.append(
                "name",
                this.$route.query.name ? this.$route.query.name : "订单"
            );
            params_file.append(
                "category",
                this.$route.query.category ? this.$route.query.category : "3"
            );
            params_file.append("file", xmlFile);
            // params_file.append(
            //     "configVo",
            //     (data.rejectNode && JSON.stringify(data.rejectNode)) ?? ""
            // );
            // const params = {
            //     name: this.$route.query.name ? this.$route.query.name : "订单",
            // category: this.$route.query.category
            //     ? this.$route.query.category
            //     : "3",
            //     file: xmlFile,
            //     id: Cookies.get("userId"),
            //     configVoList: data.rejectNode,
            // };
            if (this.type == "update") {
                // params.modelId = this.modelId;
                params_file.append("modelId", this.modelId);
            }
            // console.log(data);
            // return;
            let params = {
                id: "",
                configVoList: data.rejectNode,
            };
            try {
                let id = await this.saveFile(params_file);
                params.id = id;
                this.saveConfig(params);
            } catch (error) {
                this.$message({
                    message: "保存失败！",
                    type: "error",
                });
                console.log(error);
            }
        },
        saveFile(params) {
            console.log(1);
            return new Promise((resolve, reject) => {
                saveXml(params)
                    .then((res) => {
                        if (res.code == 200 && res.data) {
                            resolve(res.data);
                        } else {
                            throw new Error(res.msg);
                        }
                    })
                    .catch((err) => {
                        reject(err);
                    });
            });
        },
        saveConfig(params) {
            console.log(2);
            if (!params?.id) return;
            SaveModelConfig(params).then((res) => {
                if (res.code == 200) {
                    this.$message({
                        message: "保存成功",
                        type: "success",
                    });
                    this.$modal.msgSuccess(res.msg);
                    // 关闭当前标签页并返回上个页面
                    this.$router.go(-1);
                }
            });
        },
        /** 指定流程办理人员列表 */
        getDataList() {
            // userList().then(res => {
            //   res.data.forEach(val => {
            //     val.userId = val.userId.toString();
            //   })
            //   this.users = res.data;
            //   // let arr = {nickName: "流程发起人", userId: "${INITIATOR}"}
            //   // this.users.push(arr)
            // });
            // roleList().then(res => {
            //   res.data.forEach(val => {
            //     val.roleId = val.roleId.toString();
            //   })
            //   this.groups = res.data;
            // });
            // expList().then(res => {
            //   this.exps = res.data;
            // });
        },
        /** 展示xml */
        showXML(xmlData) {
            this.xmlTitle = "xml查看";
            this.xmlOpen = true;
            this.xmlData = vkBeautify.xml(xmlData);
        },
    },
};
</script>
<style lang="scss" scoped>
.headerTit {
    width: 100%;
    height: 30px;
    line-height: 30px;
    margin: 10px;
}

.content-box {
    line-height: 10px;
}

// 修改对话框高度
.showAll_dialog {
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;

    ::v-deep .el-dialog {
        margin: 0 auto !important;
        height: 80%;
        overflow: hidden;
        background-color: #ffffff;

        .el-dialog__body {
            position: absolute;
            left: 0;
            top: 54px;
            bottom: 0;
            right: 0;
            z-index: 1;
            overflow: hidden;
            overflow-y: auto;
            // 下边设置字体，我的需求是黑底白字
            color: #ffffff;
            padding: 0 15px;
        }
    }
}
</style>
